<template>
  <div class="resume_header">
    <span>在招岗位</span>
    <el-button type="primary" class="addJob_btn" @click="handleAdd()">添加岗位</el-button>
  </div>
  <div class="resume_center">

    <el-table :data="filterTableData.slice((page - 1) * limit, page * limit)
    " style="width: 100%" height="520px" size="large" @filter-change="tablesort">
      <el-table-column class="table_colum" label="岗位名称" size="large" prop="jobName" sortable column-key="jobIndustry"
        :filters="filterJobNameData" >
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="380px">
            <template #default>
              <div>岗位名称: {{ scope.row.jobName }}</div>
              <div>工作地址: {{ scope.row.jobAddress }}</div>
              <div>岗位类型: {{ scope.row.jobNature }}</div>
              <div>学历要求: {{ scope.row.jobEdu }}</div>
              <div>年龄要求: {{ scope.row.jobAge }}</div>
              <div>工作经验: {{ scope.row.jobEx }}</div>
              <div>工作薪资: {{ scope.row.jobSalary }}</div>
              <div>所属行业: {{ scope.row.jobIndustry[1] }}</div>
            </template>
            <template #reference>
              <span class="jobName_tag">{{ scope.row.jobName }}</span>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="HR姓名" prop="hrName" sortable width="220" column-key="hrName" :filters="filterHRData">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="200px">
            <template #default>
              <div>HR姓名: {{ scope.row.hrName }}</div>
              <div>联系电话: {{ scope.row.hrPhone }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.hrName }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag type="success" size="default">{{ scope.row.jobState }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="default" placeholder="岗位搜索" />
        </template>
        <template #default="scope">

          <el-button size="default" type="primary" @click="handleEdit(scope.$index, scope.row)"
            v-show="scope.row.isCurrentHR == 'true' && scope.row.isPublishing == 'true'">
            编辑</el-button>
          <el-popconfirm width="220" confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" title="是否确认操作?"
            cancel-button-type="info" @confirm="handleStop(scope.$index, scope.row)">
            <template #reference>
              <el-button size="default" type="danger" v-show="scope.row.isCurrentHR == 'true'">停止招聘</el-button>
            </template>
          </el-popconfirm>


        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <Pagination :page="page" :limit="limit" :handleSizeChange="handleSizeChange"
        :handleCurrentChange="handleCurrentChange" :filterTableData="filterTableData" :pagesizes="pagesizes" />
    </div>

  </div>
  <el-drawer ref="drawerRef" size="45%" v-model="dialog" :title="drawerTitle" :before-close="handleClose" direction="rtl"
    custom-class="demo-drawer">
    <div class="demo-drawer__content">
      <el-form :model="drawerForm">
        <el-form-item label="岗位名称" :label-width="formLabelWidth">
          <el-input placeholder="请输入" v-model="drawerForm.jobName" autocomplete="off" style="width:220px; " />
        </el-form-item>
        <el-form-item label="所属行业" :label-width="formLabelWidth">
          <el-cascader :options="proxy.$store.state.authState.job_industry" v-model="drawerForm.jobIndustry" clearable
            :show-all-levels="false" />
        </el-form-item>
        <el-form-item label="工作地址" :label-width="formLabelWidth">
          <el-input placeholder="请输入" v-model="drawerForm.jobAddress" autocomplete="off" style="width:220px; " />
        </el-form-item>
        <el-form-item label="岗位类型" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="drawerForm.jobNature">
            <el-option label="实习" value="实习" />
            <el-option label="兼职" value="兼职" />
            <el-option label="全职" value="全职" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="drawerForm.jobEdu">
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="研究生" value="研究生" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄要求" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="drawerForm.jobAge">
            <el-option label="年龄不限" value="年龄不限" />
            <el-option label="18岁以上" value="18岁以上" />
            <el-option label="20-45岁" value="20-45岁" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="drawerForm.jobEx" style="width:220px; ">
            <el-option label="经验不限" value="经验不限" />
            <el-option label="1年以下" value="一年以下" />
            <el-option label="2-3年" value="2-3年" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作薪资" :label-width="formLabelWidth">
          <el-input placeholder="请输入" autocomplete="off" v-model="drawerForm.jobSalary" style="width:220px; " />
        </el-form-item>

        <el-form-item label="岗位描述" :label-width="formLabelWidth">
          <el-input v-model="drawerForm.jobDetail" :autosize="{ minRows: 10, maxRows: 30 }" type="textarea"
            placeholder="岗位描述..." />
        </el-form-item>

      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">{{
          loading ? '正在提交 ...' : '提交'
        }}</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script lang='ts' setup>
import { ElDrawer, ElMessageBox } from 'element-plus'
import { template } from 'lodash'
import { computed, ref, onMounted, reactive, onBeforeMount, getCurrentInstance } from 'vue'
import { useStore } from "vuex"
import Pagination from "@/components/Pagination.vue"
import { getAllPublishingJob, confirmPublishingJob, stopPublishingJob } from "@/api/enterpriseApi"
import { getJobIndustry } from "@/api/authApi"
import { elmessage, data } from "@/hook/hook"
import { useRouter } from "vue-router"
const store = useStore()
const router = useRouter()

// @ts-ignore
const { proxy } = getCurrentInstance() // 1.获取proxy实例


// 编辑岗位信息--抽屉
const formLabelWidth = '80px'

const dialog = ref(false)
const loading = ref(false)

const drawerForm = reactive({
  jobId: "",
  hrName: '',
  hrPhone: '',
  jobName: '',
  jobNature: '',
  jobAddress: '',
  jobEdu: "",
  jobAge: "",
  jobEx: "",
  jobSalary: "",
  jobDetail: "",
  jobIndustry: ["", ""],
  operationType: ""

})

const drawerTitle = ref("")
const drawerRef = ref<InstanceType<typeof ElDrawer>>()


// 表格数据定义
interface Job {
  jobId: string
  hrName: string
  hrPhone: string
  jobName: string
  jobNature: string
  jobAddress: string,
  jobEdu: string,
  jobAge: string,
  jobEx: string,
  jobSalary: string,
  jobDetail: string,
  jobIndustry: ["", ""],
  jobState: string,
  isCurrentHR: string,

}
const tableData: Job[] = reactive([])
const search = ref('')
const filterTableData = computed(() =>

  tableData.filter(
    (data, index) =>
      !search.value ||
      // 通过岗位名称筛选
      // data.name.toLowerCase().includes(search.value.toLowerCase())
      data.jobName.toLowerCase().indexOf(search.value.toLowerCase()) !== -1
  )

)

// 定义筛选类型
interface filterType {
  text: string,
  value: string
}
var jobIndustryArr: any = reactive([])
var hrNameArr: any = reactive([])
const tableData_1: Job[] = reactive([])
const setJobIndustryArr = (arr: any) => {
  jobIndustryArr = arr
}
const getJobIndustry_1 = () => {
  return jobIndustryArr
}
const setHRNameArr = (arr: any) => {
  hrNameArr = arr
}
const getHRNameArr = () => {
  return hrNameArr
}
const tablesort = (filterArr: Job) => {
  // 清除原表格数据
  tableData.splice(0, tableData.length)

  if ((typeof (filterArr.jobIndustry)) == "object") {
    setJobIndustryArr(filterArr.jobIndustry)
  }
  if ((typeof (filterArr.hrName)) == "object") {
    setHRNameArr(filterArr.hrName)
  }

  const jobIndustryLength = getJobIndustry_1().length
  const eNameLength = getHRNameArr().length
  // 按筛选条件重新加入数据
  tableData_1.forEach((valu: any, index: any, arr_1: any) => {
    // 所有筛选重置，即最初排序
    if (eNameLength == 0 &&jobIndustryLength == 0) {
      if (tableData.findIndex((item: { jobId: string; }) => item.jobId == valu["jobId"]) == -1) {
        tableData.push(valu)
      }
    }
    // 只筛选岗位行业名称
    else if (jobIndustryLength > 0&&eNameLength == 0 ) {
      
      
      if (getJobIndustry_1().includes(valu["jobIndustry"][1])) {
        if (tableData.findIndex((item: { jobId: string; }) => item.jobId == valu["jobId"]) == -1) {
          tableData.push(valu)
        }
      }
    }
    // 只筛选hr名称
    else if (jobIndustryLength == 0&&eNameLength > 0  ) {
      if (getHRNameArr().includes(valu["hrName"])) {
        if (tableData.findIndex((item: { jobId: string; }) => item.jobId == valu["jobId"]) == -1) {
          tableData.push(valu)
        }
      }
    }
    // 筛选岗位行业名称、hr名称
    else if (jobIndustryLength > 0&&eNameLength > 0  ) {
      if (getJobIndustry_1().includes(valu["jobIndustry"][1])&&getHRNameArr().includes(valu["hrName"])) {
        if (tableData.findIndex((item: { jobId: string; }) => item.jobId == valu["jobId"]) == -1) {
          tableData.push(valu)
        }
      }
    }
  })
}

const filterJobNameData: filterType[] = reactive([])
const filterHRData: filterType[] = reactive([])


// 将编辑好的内容提交
const onClick = async () => {
  const newData = {
    ...data(),
    ...drawerForm,
  }
  await confirmPublishingJob(newData).then((res: any) => {
    if (res.data["code"] == "200") {
      elmessage(res.data["message"], res.data["type"])
    } else if (res.data["code"] == "300") {
      elmessage(res.data["message"], res.data["type"])
      setTimeout(() => {
        router.replace("/login")
      }, 500);
      localStorage.clear()
    } else {
      console.log(res.data["message"]);
    }
  })
  drawerRef.value!.close()
}

const handleClose = (done: any) => {
  drawerRef.value!.close()
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
}


// 添加岗位
const handleAdd = () => {
  dialog.value = true
  drawerTitle.value = "添加岗位"
  drawerForm.jobId = ""
  drawerForm.jobName = ""
  drawerForm.jobNature = ""
  drawerForm.jobAddress = ""
  drawerForm.jobEdu = ""
  drawerForm.jobAge = ""
  drawerForm.jobEx = ""
  drawerForm.jobSalary = ""
  drawerForm.jobDetail = ""
  drawerForm.jobIndustry = []
  drawerForm.operationType = "add"
}

// 编辑
const handleEdit = (index: number, row: Job) => {
  drawerTitle.value = "编辑岗位信息"
  dialog.value = true
  drawerForm.jobId = row.jobId
  drawerForm.hrName = row.hrName
  drawerForm.hrPhone = row.hrPhone
  drawerForm.jobName = row.jobName
  drawerForm.jobNature = row.jobNature
  drawerForm.jobAddress = row.jobAddress
  drawerForm.jobAge = row.jobAge
  drawerForm.jobEdu = row.jobEdu
  drawerForm.jobEx = row.jobEx
  drawerForm.jobSalary = row.jobSalary
  drawerForm.jobDetail = row.jobDetail
  drawerForm.jobIndustry = [row.jobIndustry["0"], row.jobIndustry["1"]]
  drawerForm.operationType = "update"
}

// 岗位停止招聘
const handleStop = async (index: number, row: Job) => {
  const newData = {
    ...data(),
    jobId: row.jobId
  }
  await stopPublishingJob(newData).then((res: any) => {
    if (res.data["code"] == "200") {
      elmessage(res.data["message"], res.data["type"])
    } else if (res.data["code"] == "300") {
      elmessage(res.data["message"], res.data["type"])
      setTimeout(() => {
        router.replace("/login")
      }, 500);
      localStorage.clear()
    } else {
      console.log(res.data["message"]);

    }
  })
  tableData.splice(index, 1)
}


// 分页器
const page = ref(1)
const pagesizes = ref([1, 2, 3, 4, 10, 20, 30, 40])
const limit = ref(10)

const handleSizeChange = (val: number) => {
  // pushTableData()
  limit.value = val
  page.value = 1

}
const handleCurrentChange = (val: number) => {
  page.value = val

}


const init = async () => {
  await getAllPublishingJob(data()).then((res: any) => {
    if (res.data["code"] == "200") {
      // console.log(res.data["message"]);
      res.data.datas.forEach((value: any, index: any, self: any) => {
        tableData.push(value)
        tableData_1.push(value)
      })
      res.data["industrys"].forEach((value: any, index: any, self: any) => {
        filterJobNameData.push(value)
      });
      res.data["hrs"].forEach((value: any, index: any, self: any) => {
        filterHRData.push(value)
      });
    } else if (res.data["code"] == "300") {
      elmessage(res.data["message"], res.data["type"])
      setTimeout(() => {
        router.replace("/login")
      }, 500);
      localStorage.clear()
    } else {
      console.log(res.data["message"]);
    }
  })
}

onBeforeMount(() => {
  getJobIndustry().then((res: any) => {
    store.state.authState.job_industry = reactive(res.data.job_industry)
  })
  init()
})


</script>
<style scoped>
.demo-drawer__footer {
  float: right;
}

.pagination {
  float: right;
  margin-right: 50px;
  /* right: 150px; */
}

.jobName_tag {
  /* background-color: #FFF; */
  color: #000;
  line-height: 80%;
  font-size: 20px;
  /* border-width: 0; */
}

/* .table_colum:hover  {
  background-color: #FFF;
  color: #000;
} */

.addJob_btn {
  margin-right: 100px;
}

.resume_center {
  font-family: '微软雅黑';
  height: 800px;
  background-color: #FFF;
}

.resume_header {
  background-color: rgb(215, 215, 215);
  height: 50px;
  display: flex;
  align-items: center;
  padding-left: 20px;
  justify-content: space-between;
}

a {
  text-decoration: none;
  color: #000;
}
</style>